package com.itheima.service;

import java.sql.SQLException;
import java.util.List;

import com.itheima.bean.PageBean;
import com.itheima.bean.Product;
import com.itheima.dao.ProductDao;
import com.itheima.utils.DataSourceUtils;

public class ProductService {

	/**
	 * 查询所有商品
	 * @return
	 * @throws SQLException 
	 */
	public List<Product> findAll() throws SQLException {
		ProductDao pd = new ProductDao();
		return pd.findAll();
	}
	/**
	 * 增加商品
	 * @param pro
	 * @throws SQLException 
	 */
	public void saveProduct(Product pro) throws SQLException {
		ProductDao pd = new ProductDao();
		pd.saveProduct(pro);
	}
	/**
	 * 根据id查询数据
	 * @param id
	 * @return
	 * @throws SQLException 
	 */
	public Product getProByPid(String id) throws SQLException {
		ProductDao pd = new ProductDao();
		return pd.getProByPid(id);
	}
	/**
	 * 根据id更新商品
	 * @param pro
	 * @throws SQLException 
	 */
	public void updatePro(Product pro) throws SQLException {
		ProductDao pd = new ProductDao();
		pd.updatePro(pro);
	}
	/**
	 * 根据id删除商品信息
	 * @param pid
	 * @throws SQLException 
	 */
	public void deletePro(String pid) throws SQLException {
		ProductDao pd = new ProductDao();
		pd.deletePro(pid);
	}
	/**
	 * 批量删除
	 * @param ids
	 * @throws SQLException 
	 */
	public void delCheck(String[] ids) throws SQLException {
		try {
			//开始事物
			DataSourceUtils.beginTransaction();
			ProductDao pd = new ProductDao();
			//遍历ids
			if(ids!=null){
				for(String id:ids){
					//调用dao完成删除
					pd.delCheck(id);
				}
			}
			
			//提交事物
			DataSourceUtils.commitAndClose();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//回滚事物
			DataSourceUtils.rollbackAndClose();
			throw e;
		}
		
	}
	
	/**
	 * 模糊查询
	 * @param name
	 * @param kw
	 * @return
	 * @throws SQLException 
	 */
	public List<Product> search(String name, String kw) throws SQLException {
		ProductDao pd = new ProductDao();
		return pd.search(name,kw);
	}
	/**
	 * 封装PageBean
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 * @throws SQLException 
	 */
	public PageBean<Product> getPageBean(int pageNumber, int pageSize) throws SQLException {
		ProductDao pd = new ProductDao();
		PageBean<Product> pb = new PageBean<Product>(pageSize, pageNumber);
		//获取每页显示的内容
		List<Product> list=pd.getList(pb);
		pb.setList(list);
		//获取总条数
		int count=pd.getPageCount();
		pb.setPageCount(count);
		return pb;
	}

}
